package pingu.reseau;

import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import pingu.reseau.messages.*;

public class ConnexionTCPActive implements Runnable {
	private Socket socket;
	private PinguServeur serveur;
	private boolean ready;
	private ObjectOutputStream sortie_socket;
	private ObjectInputStream entree_socket;
	
	public ObjectOutputStream getSortie_socket() {
		return sortie_socket;
	}

	public void setSortie_socket(ObjectOutputStream sortieSocket) {
		sortie_socket = sortieSocket;
	}

	public ObjectInputStream getEntree_socket() {
		return entree_socket;
	}

	public void setEntree_socket(ObjectInputStream entreeSocket) {
		entree_socket = entreeSocket;
	}
	
	public Socket getSocket() {
		return socket;
	}

	public void setSocket(Socket socket) throws IOException {
		this.socket = socket;
	}

	public boolean isReady() {
		return ready;
	}

	public void send(Message msg) throws IOException {
		this.sortie_socket.writeObject(msg);
	}

	public void setReady(boolean ready) {
		this.ready = ready;
	}

	public ConnexionTCPActive(Socket socketClient, PinguServeur serveur) throws IOException {
		this.socket = socketClient;
		this.serveur = serveur;
		this.ready = false;
		this.sortie_socket = new ObjectOutputStream(this.socket.getOutputStream());
		this.entree_socket = new ObjectInputStream(this.socket.getInputStream());
	}

	@Override
	public void run() {
		try {
				while(true){
				Message msg = (Message)entree_socket.readObject();
				System.out.println(socket.getInetAddress()+":"+socket.getPort()+" - "+msg);
				if("RDY".equals(msg.getType())){
					this.ready= (Boolean) msg.getValue();
				}
			}
		}
		catch (EOFException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
